package com.haois.ws.web.module.rbac.rest;

import com.haois.component.security.HandleCookie;
import com.haois.ws.common.constant.Reply;
import com.haois.ws.common.constant.ReturnState;
import com.haois.ws.common.constant.StatusCode;
import com.haois.ws.web.module.BaseController;
import com.haois.ws.web.module.rbac.daoman.Manager;
import com.haois.ws.web.module.rbac.service.ManagerService;
import com.haois.ws.common.util.MD5Coder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by haol on 2017/3/17.
 */
@RestController
@RequestMapping("/api/web/manager")
@Transactional
public class ManagerWebController extends BaseController {
    @Autowired
    private ManagerService managerService;

    private Logger logger = LoggerFactory.getLogger(ManagerWebController.class);

    /**
     * @api {POST} /api/web/manager/register 注册
     * @apiGroup webManager
     * @apiName Register
     * @apiDescription 管理员注册账户信息
     * @apiParam {String} account 账号(not null)
     * @apiParam {String} password 密码(not null)
     * @apiParam {String} mobile 联系电话(not null)
     * @apiParam {String} remark 备注
     * @apiParamExample {json} 请求样例：
     * POST /api/web/manager/register
     * {
     * "password":"test"
     * "account":"test"
     * "mobile":"17090077783"
     * "remark":"no message"
     * }
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"注册成功"
     * }
     */

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam(required = true, value = "account") String account,
                           @RequestParam(required = true, value = "password") String password,
                           @RequestParam(required = true, value = "mobile") String mobile) {
        Manager manager = new Manager();
        manager.setAccount(account);
        manager.setPassword(password);
        manager.setMobile(mobile);
        if (managerService.getByAccount(manager.getAccount()) == null) {
            managerService.add(manager);
            return new Reply(ReturnState.CODE_00, ReturnState.INSERT_SUCCESS).toJson();
        } else {
            return new Reply(ReturnState.CODE_03, ReturnState.NO_UNIQUE).toJson();
        }
    }

    /**
     * @api {PUT} /api/web/manager/modify-pwd 更新密码
     * @apiGroup webManager
     * @apiName modify-pwd
     * @apiDescription 管理员更新密码
     * @apiParam {String} oldPwd 旧密码
     * @apiParam {String} newPwd 新密码
     * @apiParamExample {json} 请求样例：
     * PUT /api/web/manager/modify-pwd
     * {
     * "oldPwd":"test","newPwd":"newTest"
     * }
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"更改成功"
     * }
     */
    @RequestMapping(value = "/modify-pwd", method = RequestMethod.PUT)
    public String modifyPwd(@RequestParam(required = true, value = "oldPwd") String oldPwd, @RequestParam(required = true, value = "newPwd") String newPwd,
                            HttpServletResponse response, HttpServletRequest request) {
        String mid = handleToken.getWebSubject(request);
        boolean success = managerService.modifyPwd(mid, oldPwd, newPwd);
        if (success) {
            HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
            return new Reply(ReturnState.CODE_00, ReturnState.UPDATE_SUCCESS).toJson();
        } else {
            return new Reply(ReturnState.CODE_10, ReturnState.FAIL + ":密码不正确").toJson();
        }
    }

    /**
     * @api {PUT} /api/web/manager/update 更新信息
     * @apiGroup webManager
     * @apiName update
     * @apiDescription 管理员更新信息
     * @apiParam {String} mobile 联系电话
     * @apiParamExample {json} 请求样例：
     * PUT /api/web/manager/update
     * {
     * "mobile":"18888888888",
     * "remark":"this is remark"
     * }
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"更改成功"
     * }
     */

    @RequestMapping(value = "/update", method = RequestMethod.PUT, params = {"name", "mobile"})
    public String update(Manager manager, HttpServletRequest request) {
        String mid = handleToken.getWebSubject(request);
        manager.setId(mid);
        managerService.update(manager);
        return new Reply(ReturnState.CODE_00, ReturnState.UPDATE_SUCCESS).toJson();
    }

    /**
     * @api {GET} /api/web/manager/self 获取登录管理员
     * @apiGroup webManager
     * @apiName seeSelf
     * @apiDescription 获取当前登录的管理员的个人信息
     * @apiParamExample {json} 请求样例：
     * {GET} /api/web/manager/self
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"获取成功","data":{"id":"f3b66fb8-95de-4d1e-9380-12f8f5b9a4e9","account":"test","password":"889255f1c9c8f12a353be255f78a848b","createTime":"Tue Apr 18 22:00:43 CST 2017","LoginTime":"Apr 26, 2017 6:20:48 PM","mobile":"17090077783"}
     * }
     */
    @RequestMapping(value = "/self", method = RequestMethod.GET)
    public String seeSelf(HttpServletRequest request) {
        String account = handleToken.getWebSubject(request);
        Manager manager = managerService.getByAccount(account);
        Reply<Manager> reply = new Reply<Manager>(ReturnState.CODE_00, "获取成功", manager);
        reply.dataIsEmpty();
        return reply.toJson();
    }


    /**
     * @api {GET} /api/web/manager/{account} 获取管理员ByAccount
     * @apiGroup webManager
     * @apiName getByAccount
     * @apiParam {String} account 账号
     * @apiDescription 获取管理员信息ByAccount
     * @apiParamExample {json} 请求样例：
     * {GET} /api/web/manager/test
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"获取成功","data":{"id":"f3b66fb8-95de-4d1e-9380-12f8f5b9a4e9","account":"test","password":"889255f1c9c8f12a353be255f78a848b","createTime":"Tue Apr 18 22:00:43 CST 2017","LoginTime":"Apr 26, 2017 6:20:48 PM","mobile":"17090077783"}
     * }
     */
    @RequestMapping(value = "/{account}", method = RequestMethod.GET)
    public String getByAccount(@PathVariable String account) {
        Manager manager = managerService.getByAccount(account);
        Reply<Manager> reply = new Reply(ReturnState.CODE_00, ReturnState.INSERT_SUCCESS, manager);
        reply.dataIsEmpty();
        return reply.toJson();
    }



    /**
     * @api {GET} /api/web/manager/check-exist  检测账号是否存在
     * @apiGroup webManager
     * @apiName check
     * @apiParam {String} account 管理员账号
     * @apiDescription 检测管理员账号是否存在, 用于管理员注册前的检测
     * @apiParamExample {json} 请求样例：
     * GET /api/web/manager/i/organize_id/check-exist
     * { "account":"test" }
     * @apiSuccessExample {json} 返回样例:
     * { "存在":10;"不存在":00}
     */
    @RequestMapping(value = "/check-exist", method = RequestMethod.GET)
    public String checkExist(@RequestParam(required = true, value = "account") String account) {
        Manager manager = managerService.getByAccount(account);
        if (manager == null) {
            return new Reply(ReturnState.CODE_00, " 账号不存在，可注册").toJson();
        } else {
            return new Reply(ReturnState.CODE_10, "账号已存在，请更换账号").toJson();
        }

    }

    /**
     * @api {GET} /api/web/manager/check-self  检验是否为本人
     * @apiGroup webManager
     * @apiName checkSelf
     * @apiParam {String} password 密码
     * @apiDescription 检验是否为本人，用于对一些敏感操作验证比如删除组织
     * @apiParamExample {json} 请求样例：
     * GET /api/web/manager/check-self
     * {
     * "password":"test"
     * }
     * @apiSuccessExample {json} 返回样例:
     * {
     * "00":"校验通过","10":"校验不通过";
     * }
     */
    @RequestMapping(value = "/check-self", method = RequestMethod.GET)
    public String checkSelf(HttpServletRequest request, @RequestParam(required = true, value = "password") String password) {
        String mid = handleToken.getWebSubject(request);
        Manager manager = managerService.getByAccount(mid);
        String MD5 = MD5Coder.encodeCombine(manager.getAccount(), password);
        if (manager.getPassword().equals(MD5)) {
            return new Reply(ReturnState.CODE_00, "校验通过").toJson();
        } else {
            return new Reply(ReturnState.CODE_10, "校验不通过").toJson();
        }
    }



}
